package com.lzq.shiro.controller;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lzq.shiro.config.Constant;
import com.lzq.shiro.config.util.ShiroUtil;
import com.lzq.shiro.entity.ResponseEntity;
import com.lzq.shiro.entity.UserInfo;
import com.lzq.shiro.entity.UserRole;
import com.lzq.shiro.service.SysUserRoleService;
import com.lzq.shiro.service.UserInfoService2;
import com.lzq.shiro.vo.RspUtil;




@Controller
@RequestMapping("/userRole")
public class SysUserRoleController {
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@Autowired
	private UserInfoService2 sysUserInfoService2; 
	
	@RequestMapping(method=RequestMethod.PUT)
	@ResponseBody
	public Map<String , Object> modifyUserRole(@RequestBody UserRole userRole) {
		try {
			
			Map<String , Object> result =  sysUserRoleService.modify(userRole);
			if(Constant.SUCCESS_STATUS.equals(result.get(Constant.RSP_STATUS))) {
				// 如果用户角色修改成功
				UserInfo queryParams = new UserInfo();
				queryParams.setUid(userRole.getUid());
				UserInfo userInfo = sysUserInfoService2.query(queryParams);
				if(userInfo != null) {
					// 更新shiro中的用户权限
					ShiroUtil.reloadAuthorizing(userInfo);
				}
			}
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage() , e);
			return RspUtil.rspErrMap(ResponseEntity.CORE_EXCP.getCode(), ResponseEntity.CORE_EXCP.getMessage());
		}
	}
	@GetMapping
	public void test() {
		throw new UnauthorizedException();
	}
	
	
}
